#include <iostream>
#include <semaphore.h>
#include <cstdlib>
#include <ctime>
#include <unistd.h>
#include "ringqueue.hpp"

void *Producer(void *arg)
{
    RingQueue<int> *rq = (RingQueue<int> *)arg;
    while (true)
    {
        sleep(1);
        //  1.获取数据或制作任务 ---- 也有时间花费
        int in = rand() % 100 + 1;
        // 2.推送到环形队列中
        rq->push(in);
        cout << "producer[" << pthread_self() % 10000 << "]: 生产了一个数据 " << in << endl;
    }
}

void *Consumer(void *arg)
{
    RingQueue<int> *rq = (RingQueue<int> *)arg;
    while (true)
    {
        //sleep(1);
        int out;
        // 1.从环形队列中获取数据
        rq->pop(&out);
        cout << "consumer[" << pthread_self() % 10000 << "]: 消费了一个数据 " << out << endl;
        // 2.处理数据 ---- 也有时间花费
    }
}

int main()
{
    srand((unsigned int)time(nullptr));
    RingQueue<int> *rq = new RingQueue<int>();
    pthread_t p[2], c[3];
    pthread_create(p, nullptr, Producer, rq);
    pthread_create(p + 1, nullptr, Producer, rq);
    pthread_create(c, nullptr, Consumer, rq);
    pthread_create(c + 1, nullptr, Consumer, rq);
    pthread_create(c + 2, nullptr, Consumer, rq);
    
    for (int i = 0; i < 2; ++i)
        pthread_join(p[i], nullptr);
    for (int i = 0; i < 3; ++i)
        pthread_join(c[i], nullptr);
    delete rq;
    return 0;
}